package com.common.controller;

import com.common.config.CommonApplicationConfig;
import com.common.constanct.CommonUtils;
import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.model.SystemApplicationModel;
import com.common.mysql.SearchPageResult;
import com.common.mysql.Where;
import com.common.sevice.SystemApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("/v1/system-application")
public class SystemApplicationController extends Controller<String, SystemApplicationService, SystemApplicationModel> {

    @Autowired
    private CommonApplicationConfig config;

    @Override
    public ApiResult searchPage(@RequestParam(defaultValue = "1", required = false) int page,
                                @RequestParam(defaultValue = "10", required = false) int limit,
                                @RequestParam Map<String, Object> params) {
        SearchPageResult<SystemApplicationModel> result = new SearchPageResult<>();
        result.setPage(page);
        result.setLimit(limit);
        Where where = Where.build().field("del_flag").equal(0);
        if(!ObjectUtils.isEmpty(params.get("name"))){
            where.and().field("name").equal(params.get("name"));
        }
        if(!ObjectUtils.isEmpty(params.get("userName"))){
            where.and().field("user_name").equal(params.get("userName"));
        }
        int totalCount = service.count(where);
        List<SystemApplicationModel> resultList = service.search(where.limit(page, limit));
        result.setList(resultList);
        result.setTotalCount(totalCount);
        return ApiResult.success(result);
    }

    @GetMapping("/info")
    public ApiResult info(){
        String appId = config.getAppId();
        if (!StringUtils.hasText(appId)){
            throw new ErrorException("appId不能为空！");
        }
        return getById(appId);
    }


    @Override
    public ApiResult add(@RequestBody SystemApplicationModel model) {
        model.setId(CommonUtils.get32UUID());
        //初始化web和service相关初始化脚本
        service.addTemplate(model);
        return super.add(model);
    }

    @Override
    public ApiResult delete(@RequestBody SystemApplicationModel model) {
        service.deleteChildren(model);
        return super.delete(model);
    }

    @PostMapping("/generateSql")
    public ApiResult generateSql(@RequestBody Map<String,String> params){
        String appId = params.get("appId");
        if (!StringUtils.hasText(appId)){
            throw new ErrorException("appId不能为空！");
        }
        String initSql = service.generateSql(appId);
        return ApiResult.success(initSql);
    }

}
